<template>
  <div class="login">
    <vue-particles
          class="login-bg"
          color="#39AFFD"
          :particleOpacity="0.7"
          :particlesNumber="100"
          shapeType="circle"
          :particleSize="4"
          linesColor="#8DD1FE"
          :linesWidth="1"
          :lineLinked="true"
          :lineOpacity="0.4"
          :linesDistance="150"
          :moveSpeed="3"
          :hoverEffect="true"
          hoverMode="grab"
          :clickEffect="true"
          clickMode="push"
          >
          </vue-particles>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <img v-if="logo" :src="logo" class="login-logo" />
      <h3 class="title">三明市涉案财物集中管理平台
      <!-- <el-tooltip effect="dark" content="APP下载" placement="right">
        <el-tag plain size="mini" type="warning">v.1.0.0</el-tag>
        <img slot="content" src="../assets/images/down-51.png" style="width: 30rem;"/>
      </el-tooltip> -->
      </h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaOnOff">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="手机验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />

        </el-input>
        <div class="login-code">
<!--          <img :src="codeUrl" @click="getCode" class="login-code-img"/>-->
          <el-button @click="showDialog">获取验证码</el-button>
        </div>
      </el-form-item>
      <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px; color: #FFFFFF;">记住密码</el-checkbox> -->
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;float: left;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>


    <!--  底部  -->
    <div class="el-login-footer">
      <span>技术公司: 三明市安保信息科技有限公司</span>
    </div>
    <div v-if="this.dialogShow" class="modal-overlay">
      <el-form class="dialogShow" ref="dialogForm" :model="dialogForm" :rules="loginRules" v-show="this.dialogShow" style="height: 16%;">
        <el-form-item prop="code" v-if="captchaOnOff">
          <el-input
            v-model="dialogForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="sendPhone">获取手机验证码</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </div>


  </div>
</template>

<script>
import {getCodeImg, getPhoneNumber, getPublicKey, getUserPhoneNumber} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt,encryptParam } from '@/utils/jsencrypt';
import logoImg from '@/assets/images/profile_logo.png';
import Vue from 'vue'
import VueParticles from 'vue-particles'
import SIdentify from "@/views/SIdentify.vue";

Vue.use(VueParticles)

export default {
  components:{SIdentify},
  name: "Login",
  props: {
    width: { type: Number, default: 120 },
    height: { type: Number, default: 40 }
  },
  data() {
    return {
      dialogShow: false,
      codeUrl: "",
      logo: logoImg,
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      dialogForm:{
        code: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],

      },
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined,
      queryN:undefined,
      queryP:undefined,
      keyStr:undefined,
      keyUuid:undefined,
      captchaCode: this.generateCode(),
      result: undefined,
      phoneCode:undefined,
      userPhoneNumber:undefined,
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    if(this.$router.currentRoute.query.n){
      this.queryN = this.$router.currentRoute.query.n;
    }
    if(this.$router.currentRoute.query.p){
      this.queryP = this.$router.currentRoute.query.p;
    }
    if(this.queryN && this.queryP){
      this.loginForm = {
        username: this.queryN,
        password: this.queryP
      };
      this.$store.dispatch("Login", this.loginForm).then(() => {
        this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
      }).catch(() => {
        this.loading = false;
        if (this.captchaOnOff) {
          this.getCode();
        }
      });
    }
    this.getCode();
    this.getKey();
    this.getCookie();
  },
  methods: {
    closeDialog(){
      this.dialogShow = false
    },
    showDialog(){
      if(this.loginForm.username == ""){
        this.$message.error('请完善信息')
      }else{
        //获取用户手机号
        this.dialogShow = true
        this.getCode();
        //获取手机号
        const userName = this.loginForm.username
        getUserPhoneNumber({userName}).then(res => {
          this.userPhoneNumber = res.data
        });
      }
    },
    sendPhone(){
      if(this.dialogForm.code === this.result){
        //发送手机验证码
        const phoneNumber = this.userPhoneNumber
        getPhoneNumber({phoneNumber}).then(res => {
          //关闭弹框
          this.dialogShow = false
          this.$message.success('验证码发送成功！');
        }).catch(() => {
          this.loading = false;
          if (this.captchaOnOff) {
            this.getCode();
          }
        });
      }
    },
    generateCode(length = 6) {
      let result = '';
      // 排除易混淆字符（0/O, 1/I等）
      const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';

      for(let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      this.code = result;
      return result;
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.data.captchaOnOff === undefined ? true : res.data.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.data.img;
          this.loginForm.uuid = res.data.uuid;
          this.result = res.data.result;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    getKey(){
      getPublicKey().then(res => {
          this.keyStr = res.data.publicKey;
          this.keyUuid = res.data.uuid;
      });
    },
    passwordEncryption (param) {
      let passwordEncryp = encryptParam(param,this.keyStr) // 对密码进行加密
      return passwordEncryp
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }

          let params = {
            username:this.loginForm.username,
            password:this.passwordEncryption(this.loginForm.password),
            keyUuid:this.keyUuid,
            code:this.loginForm.code,
            uuid:this.loginForm.uuid
          };
          this.$store.dispatch("Login", params).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            if (this.captchaOnOff) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/loginBackgroundImage.jpg");
   // background-image: url("../assets/images/login.png");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #b9eff4;
  font-size: 26px;
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.dialogShow{
  position:absolute;
  border-radius: 6px;
  background: #051d469e;
  width: 400px;
  padding: 25px 25px 5px 25px;
  border: 3px solid #1e4a85;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-form {
  position:absolute;
  border-radius: 6px;
  background: #051d469e;
  width: 400px;
  padding: 25px 25px 5px 25px;
  border: 3px solid #1e4a85;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
.login-logo{
  width: 60px;
  height: 60px;
  margin: 0px auto 20px auto;
  display: block;
}
.login-bg{
   width: 100%;
    height: 100%;
}

</style>
